/*
 * @Descripttion: 
 * @version: 
 * @Author: 刘冰见
 * @Date: 2024-10-09 08:52:19
 * @LastEditors: 刘冰见
 * @LastEditTime: 2025-10-25 12:32:49
 */
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:sousuoapp/net/interceptor/custom_interceptor.dart';
import 'package:sousuoapp/net/method/bese_method.dart';

/// 网络管理
class NetworkManager {
  static NetworkManager? _instance;

  late Dio dio;

  NetworkManager._insternal() {
    _instance = this;
    _instance!._int();
  }
  factory NetworkManager() => _instance ?? NetworkManager._insternal();

  final CancelToken _cancelToken = CancelToken();

  static NetworkManager getInstance() {
    _instance ??= NetworkManager._insternal();
    return _instance!;
  }

  _int() {
    // 配置BaseOptions
    BaseOptions options = BaseOptions(
        baseUrl:
            'https://www.cqdykj.com:8012/share_glasses_manager_api/', //小豫科技
        // baseUrl: 'https://www.xiyaodata.com:8012/share_glasses_manager_api/', //夕瑶数据
        //连接超时
        connectTimeout: const Duration(seconds: 15),
        //接收超时
        receiveTimeout: const Duration(seconds: 15),
        //内容类型r
        contentType: 'application/json;Charset=UTF-8',
        //响应数据类型：Jsonsss
        responseType: ResponseType.json);
    dio = Dio(options);
    dio.interceptors.add(CustomInterceptor());
  }

  ///网络请求
  Future<T> request<T>(String path,
      {BaseMethod method = BaseMethod.get,
      Map<String, dynamic>? params,
      data,
      CancelToken? cancelToken,
      Options? options}) async {
    const methodValues = {
      BaseMethod.get: 'get',
      BaseMethod.post: 'post',
      BaseMethod.put: 'put',
      BaseMethod.delete: 'delete',
      BaseMethod.patch: 'patch',
      BaseMethod.head: 'head',
    };
    options ??= Options(method: methodValues[method]);

    try {
      Response response;
      response = await dio.request(path,
          data: data,
          queryParameters: params,
          cancelToken: cancelToken ?? _cancelToken,
          options: options);
      return response.data;
    } on DioException {
      rethrow;
    }
  }
}
